#include <SDL2/SDL.h>

#define BLOCK_SIZE 4096000
static Uint8 *audio_buf = NULL;
static    size_t buffer_len;
static    Uint8 *audio_pos; 


void read_audio_data(void *udata, Uint8 * stream, int len){
    if(!buffer_len){
        return;
    }

    SDL_memset(stream, 0, len);
    len = (len < buffer_len)?len:buffer_len;
    SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);
    audio_pos += len;
    buffer_len -=len;
}
int main(int argc, char *argv[])
{
    int ret = 0;
    char *path;
    FILE *pcm_file;
    Uint8 *audio_buf = NULL;

    if (argc < 2)
    {
        SDL_Log("param error\n");
        return -1;
    }
    path = argv[1];
    ret = SDL_Init(SDL_INIT_AUDIO);
    if (ret != 0)
    {
        SDL_Log("Failed to initial SDL\n");
        return ret;
    }

    pcm_file = fopen(path, "rb");

    if (!pcm_file)
    {
        SDL_Log("Failed to open file %s\n", path);
        ret = -1;
        goto _EXIT;
    }

    audio_buf = (Uint8 *)malloc(BLOCK_SIZE);
    if (!audio_buf)
    {
        SDL_Log("Failed to malloc  buf \n");
        ret = -1;
        goto _EXIT;
    }

   SDL_AudioSpec spec; 
   spec.freq = 44100;
   spec.format = AUDIO_S16SYS;
   spec.channels = 2;
   spec.callback = read_audio_data;
   spec.userdata = NULL;
   //打开音频设备
   ret = SDL_OpenAudio(&spec, NULL); 
   if (ret != 0)
    {
        SDL_Log("Failed to open audio\n");
        return ret;
    }
    SDL_PauseAudio(0);

    do{
        buffer_len  = fread(audio_buf, 1, BLOCK_SIZE, pcm_file);
        audio_pos = audio_buf;
        while (audio_pos < audio_buf + buffer_len)
        {
            SDL_Delay(1);
        }
    }while (!buffer_len);
    SDL_CloseAudio();
    ret = 0;
_EXIT:
    SDL_Quit();
    if (audio_buf)
    {
        free(audio_buf);
    }
    if (pcm_file)
    {
        fclose(pcm_file);
    }
    return ret;
}